﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Xml;
using System.Net;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace CNative
{/// <summary>
 /// 日志等级
 /// </summary>
    public enum EnumLogPoiority
    {
        Undefine,//未知的
        Normal,//一般
        High
    }

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum EnumLogType
    {
        Info,
        Error,
        Warn
    }
    /// <summary>
    /// 日志处理类
    /// </summary>
    public class FgLogHelper
    {
        //全局静态FileConfigurationSource
        public static FileConfigurationSource m_FileSource = null;
        //日志静态变量
        //private static List<EntityLogNew> m_ListLogEntity = new List<EntityLogNew>();
        /// <summary>
        /// LOG文件XmlDocument
        /// </summary>
        public static XmlDocument m_XmlDoc = null;

        /// <summary>
        /// TraceEventType类新转换
        /// </summary>
        /// <param name="type">日志类型</param>
        /// <returns>返回TraceEventType</returns>
        //private static TraceEventType MapType(EnumLogType type)
        //{
        //    switch (type)
        //    {
        //        case EnumLogType.Error: { return TraceEventType.Error; }
        //        case EnumLogType.Warn: { return TraceEventType.Warning; }
        //        case EnumLogType.Info: { return TraceEventType.Information; }
        //        default: { return TraceEventType.Information; }
        //    }
        //}

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg">日志内容</param>
        public static void Write(string msg)
        {
            Write(msg, string.Empty, EnumLogPoiority.Normal, EnumLogType.Info, new StringBuilder());
        }

        /// <summary>
        /// 写日志
        /// 带扩展属性，可传入方法名称等
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="ExtendInfo">扩展消息</param>
        public static void Write(string msg, StringBuilder _ExtendInfo)
        {
            Write(msg, string.Empty, EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
        }

        /// <summary>
        /// 写日志，带标题
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="title">日志标题</param>
        public static void Write(string msg, string title)
        {
            Write(msg, title, EnumLogPoiority.Normal, EnumLogType.Info, new StringBuilder());
        }

        /// <summary>
        /// 写日志，带标题
        /// 带扩展属性，可传入方法名称等
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="title">日志标题</param>
        /// <param name="ExtendInfo">扩展消息</param>
        public static void Write(string msg, string title, StringBuilder _ExtendInfo)
        {
            Write(msg, title, EnumLogPoiority.Normal, EnumLogType.Info, _ExtendInfo);
        }

        /// <summary>
        /// 写日志，带标题、日志等级
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="title">日志标题</param>
        /// <param name="poiority">日志等级</param>
        public static void Write(string msg, string title, EnumLogPoiority poiority)
        {
            Write(msg, title, poiority, EnumLogType.Info, new StringBuilder());
        }

        /// <summary>
        /// 写日志，带标题、日志等级
        /// 带扩展属性，可传入方法名称等
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="title">日志标题</param>
        /// <param name="poiority">日志等级</param>
        /// <param name="ExtendInfo">扩展消息</param>
        public static void Write(string msg, string title, EnumLogPoiority poiority, StringBuilder _ExtendInfo)
        {
            Write(msg, title, poiority, EnumLogType.Info, _ExtendInfo);
        }

        /// <summary>
        /// 写日志，带标题、日志等级、日志类型
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="title">日志标题</param>
        /// <param name="poiority">日志等级</param>
        /// <param name="type">日志类型</param>
        public static void Write(string msg, string title, EnumLogPoiority poiority, EnumLogType type)
        {
            Write(msg, title, poiority, type, new StringBuilder());
        }

        /// <summary>
        /// 写日志，带标题、日志等级、日志类型
        /// 带扩展属性，可传入方法名称等
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="title">日志标题</param>
        /// <param name="poiority">日志等级</param>
        /// <param name="type">日志类型</param>
        /// <param name="ExtendInfo">扩展消息</param>
        public static void Write(string msg, string title, EnumLogPoiority poiority, EnumLogType type, StringBuilder _ExtendInfo)
        {
            try
            {
                string _iptemp = string.Empty;

                WriteLog(msg + "       ;      " + title);

                //if (FgPubVar.g_LogCategory != null)
                //{
                //    _iptemp = GetIPAndPort();
                //    var _logEntity = m_ListLogEntity.Find(p => p.LogIp == _iptemp);
                //    if(_logEntity!=null&&_logEntity.LogOnTime<DateTime.Now.AddMinutes(-10))//十分钟自动关闭日志
                //    {
                //        FgPubVar.g_ListLogEntity.RemoveAll(p=>p.LogIp== _iptemp);
                //        m_ListLogEntity.RemoveAll(p => p.LogIp == _iptemp);
                //        return;
                //    }
                //    if (!FgPubVar.g_ListLogEntity.Exists(p => p.LogIp == _iptemp || p.LogIp == "::1" || p.LogIp == "127.0.0.1"))
                //        return;

                //    using (LogWriter lw = new LogWriterFactory(m_FileSource).Create())
                //    {
                //        LogEntry log = new LogEntry();
                //        log.TimeStamp = log.TimeStamp.ToLocalTime();
                //        log.Message = msg;
                //        log.Title = _iptemp + "|" + title;
                //        log.Severity = MapType(type);
                //        log.Priority = (int)poiority;

                //        lw.Write(log, FgPubVar.g_LogCategory, (int)poiority, -1, GetInfoType(type), FgFuncStr.SetStrNSP(_iptemp, 64) + FgFuncStr.NullToStr(_ExtendInfo.ToString()));
                //        new FgLogHelperPro().Write.Info(title + "\r\t" + msg);
                //    }
                //}
            }
            catch (Exception ex) { new FgLogHelperPro().Write.Fatal("日志写入失败！", ex); }
        }

        public static void WriteLog(string Text) { 
            //new FgLogHelperPro().Write.Fatal(Text);
        }

        /// <summary>
        /// 消息类型标准转换
        /// </summary>
        /// <param name="type">消息类型</param>
        /// <returns>标准类型TraceEventType</returns>
        private static TraceEventType GetInfoType(EnumLogType type)
        {
            TraceEventType _TrEvtype = TraceEventType.Information;
            switch (type)
            {
                case EnumLogType.Error:
                    _TrEvtype = TraceEventType.Error;
                    break;
                case EnumLogType.Info:
                    _TrEvtype = TraceEventType.Information;
                    break;
                case EnumLogType.Warn:
                    _TrEvtype = TraceEventType.Critical;
                    break;
                default:
                    _TrEvtype = TraceEventType.Information;
                    break;
            }
            return _TrEvtype;
        }

        /// <summary>
        /// 获取服务器XML文件,根据相关条件检索节点
        /// </summary>
        /// <param name="SourceName">XML文件字符串</param>
        /// <returns></returns>
        public static string GetFileConfigurationSource(string SourceName)
        {
            //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //ConfigurationSourceSection section = (ConfigurationSourceSection)config.GetSection(ConfigurationSourceSection.SectionName);
            //FileConfigurationSourceElement elem = (FileConfigurationSourceElement)section.Sources.Get(SourceName);
            XmlDocument ldoc = new XmlDocument();
            switch (SourceName)
            {
                case "Log Configuration Source":
                    ldoc.Load(AppDomain.CurrentDomain.BaseDirectory + "\\log.config");
                    break;
            }
            return ldoc.OuterXml;
        }

        /// <summary>
        /// 配置文件定向
        /// </summary>
        public static void GetFSEnty()
        {
            //获取重定向配置文件资源  
            //FgFuncXml.CreateOrUpdateXmlAttributeByXPath(AppDomain.CurrentDomain.BaseDirectory + "log.config", "configuration//loggingConfiguration//listeners//add", "fileName", "Log\\" + DateTime.Now.ToString("yyyyMMdd") + ".log");
            //m_FileSource = new FileConfigurationSource(AppDomain.CurrentDomain.BaseDirectory + "log.config");
        }

        //    /// <summary>
        //    /// 重新设置平台日志参数
        //    /// </summary>
        //    /// <param name="categs"></param>
        //    public void setLogCategory(params object[] formats)
        //    {
        //        List<string> cateList = new List<string>();
        //        for (int i = 0; i < formats.Length; i++)
        //        {
        //            cateList.Add((string)formats[i]);
        //        }
        //        FgPubVar.g_LogCategory = cateList.ToArray();

        //        Write("开启日志成功", "", EnumLogPoiority.Normal, EnumLogType.Info);
        //    }


        //    /// <summary>
        //    /// 获取客户端IP和端口
        //    /// </summary>
        //    /// <returns></returns>
        //    private static string GetIPAndPort()
        //    {
        //        //提供方法执行的上下文环境   
        //        OperationContext context = OperationContext.Current;
        //        string _iptemp = string.Empty;
        //        if (context != null)
        //        {
        //            //获取传进的消息属性   
        //            MessageProperties properties = context.IncomingMessageProperties;
        //            //获取消息发送的远程终结点IP和端口   
        //            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

        //            _iptemp = endpoint.Address;
        //        }

        //        if (_iptemp == "" || _iptemp == "127.0.0.1" || _iptemp.Length <= 3)
        //        {
        //            foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
        //            {
        //                if (!ip.IsIPv6LinkLocal)
        //                {
        //                    _iptemp = ip.ToString();
        //                    break;
        //                }
        //            }
        //        }
        //        return string.Format("{0}", _iptemp);
        //    }

        //    /// <summary>
        //    /// 应用服务器开启针对客户端ip开启日志功能
        //    /// </summary>
        //    /// <param name="ipaddress"></param>
        //    /// <param name="logflag"></param>
        //    /// <returns></returns>
        //    public static bool Setlog(string ipaddress, bool logflag)
        //    {
        //        if (ipaddress.Equals("8.8.8.8")) return true;
        //        bool _bz = false;
        //        if (logflag)//加入日志实体
        //        {
        //            foreach (EntityLog _LogEntity in FgPubVar.g_ListLogEntity)
        //            {
        //                if (_LogEntity.LogIp == ipaddress)
        //                {
        //                    return true;
        //                }
        //            }
        //            EntityLogNew _LogEntityNew = new EntityLogNew();
        //            _LogEntityNew.LogIp = ipaddress;
        //            _LogEntityNew.LogOnTime = DateTime.Now;
        //            EntityLog _LogEntityOld = new EntityLog();
        //            _LogEntityOld.LogIp = ipaddress;
        //            m_ListLogEntity.Add(_LogEntityNew);
        //            FgPubVar.g_ListLogEntity.Add(_LogEntityOld);
        //            return true;
        //        }
        //        else//移除日志实体;
        //        {
        //            foreach (EntityLog _LogEntity in FgPubVar.g_ListLogEntity)
        //            {
        //                if (_LogEntity.LogIp == ipaddress)
        //                {
        //                    FgPubVar.g_ListLogEntity.Remove(_LogEntity);
        //                    m_ListLogEntity.RemoveAll(p => p.LogIp == ipaddress);
        //                    return true;
        //                }
        //            }
        //        }
        //        return _bz;
        //    }
    }
}
